<template>
  <div class="meet_add">
    <div class="meet_add_l">
      <el-form :model="formData" :rules="rules" ref="ruleForm" size="small" label-width="100px" class="notice_form">
        <el-row>
          <el-col :span="8">
            <el-form-item label="录入日期" prop="replaceName">
              <div class="color_content">{{ formData.createTime }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="录入部门">
              <div class="color_content">{{ formData.orgName }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="录入人">
              <div class="color_content">{{ formData.userName }}</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="会议类型">
              <el-radio-group
                size="small"
                v-model="formData.meetingType"
                @input="changeType"
                :disabled="isDisabled || isEdit">
                <el-radio label="1">内部会议</el-radio>
                <el-radio label="2">外部会议</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="tip">
              注：内部会议由部门内人员参会，外部会议为跨部门会议，参会人员为全局人员，提交后需上级领导审批。
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="会议主题" prop="meetingName">
              <el-input
                v-model="formData.meetingName"
                placeholder="请输入会议主题"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 100 }"
                maxlength="100"
                show-word-limit
                :disabled="isDisabled"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="会议议程" prop="">
              <el-input
                v-model="formData.meetingContent"
                placeholder="请输入会议议程"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 100 }"
                maxlength="300"
                show-word-limit
                :disabled="isDisabled"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!isDisabled">
          <el-col :span="24">
            <div class="select-btn">
              <el-button type="primary" size="small" icon="el-icon-plus" @click="editMeetRoom">
                选择会议室及时间
              </el-button>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="会议时间" prop="meetingDate" :rules="rules.meetingDate" class="is_change">
              <el-date-picker
                size="small"
                :popper-append-to-body="false"
                v-model="formData.meetingDate"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                :editable="false"
                :disabled="isDisabled || formData.timeType === '2'"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会议地点" prop="meetingPlace">
              <el-input
                v-model="formData.meetingPlace"
                placeholder="请输入"
                maxlength="50"
                show-word-limit
                :disabled="isDisabled"
                @input="placeInput"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="会议来源" prop="meetingResource">
              <el-input
                v-model="formData.meetingResource"
                placeholder="请输入"
                maxlength="30"
                show-word-limit
                :disabled="isDisabled"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="会议资料">
              <UploadFile :file-list="formData.enclosureList" titleAdd="" v-if="!isDisabled"></UploadFile>
              <template v-else>
                <UploadPreview
                  :file-list="formData.enclosureList || []"
                  layout="list"
                  v-if="formData.enclosureList.length"></UploadPreview>
                <span v-else>无</span>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="参会人员"
              prop="userCascader"
              :rules="[{ required: true, message: '参会人员不能为空', trigger: 'change' }]">
              <el-cascader
                :key="cascaderKeyValueAll"
                class="selectStyle"
                placeholder="请选择"
                :options="userOptions"
                :props="propsCascader"
                filterable
                v-model="formData.userCascader"
                ref="cascaderAll"
                :show-all-levels="false"
                :disabled="isDisabled"
                @keydown.native.delete.capture.stop.prevent></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="btn_save" v-if="!isDisabled && !isEdit">
          <el-button @click="saveData('0')" size="small">暂存</el-button>
          <el-button @click="saveData('2')" size="small" type="primary" plain>提交并继续录入</el-button>
          <el-button size="small" type="primary" @click="saveData('1')">提交</el-button>
        </div>
        <div class="btn_save" v-if="isEdit">
          <el-button size="small" type="primary" @click="cancleMeet('1')" plain="">取消会议</el-button>
          <el-button size="small" type="primary" @click="saveData('3')">审批通过</el-button>
        </div>
      </el-form>
    </div>

    <!-- 新建 start -->
    <XnDialog
      title="选择会议室"
      :visible.sync="roomDiaShow"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      width="65%"
      class="branch_dialog"
      append-to-body
      @closed="onClose">
      <MeetRoom
        v-if="roomDiaShow"
        @appointmentSuccess="chooseMeetRoom"
        :roomInfo="roomInfo"
        :meetId="meetId"></MeetRoom>
    </XnDialog>
  </div>
</template>

<script>
import {
  getGroupUserList,
  addMeeting,
  getMeetingDetail,
  editMeeting,
  checkRoomAndTimeAuthority,
  getMeetingRoomList,
} from '@apis/meeting.js'
import moment from 'moment'
import UploadFile from '@com/UploadFile'
import XnDialog from '@com/xnDialog.vue'
import MeetRoom from './MeetRoom'
import UploadPreview from '@com/UploadPreview/index.vue'
export default {
  components: {
    UploadFile,
    XnDialog,
    MeetRoom,
    UploadPreview,
  },
  props: {
    meetId: {
      type: String,
      default: '',
    },
    isDisabled: {
      type: Boolean,
      default: false,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validFile = (rule, value, callback) => {
      if (value && value.length > 0) {
        callback()
      } else {
        callback(new Error('请上传附件'))
      }
    }
    return {
      moment: moment,
      formData: {
        id: '',
        createTime: moment().format('YYYY-MM-DD'),
        userName: JSON.parse(localStorage.PSKH_USERINFO).userName,
        orgName: JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.orgName,
        meetingType: '1',
        meetingName: '',
        meetingContent: '',
        meetingDate: [],
        meetingPlace: '',
        meetingRoomId: '',
        meetingPlaceType: '2',
        meetingResource: '',
        enclosureList: [],
        participantsList: [],
        meetingStatus: '0',
        startTime: '',
        endTime: '',
        userCascader: [],
      },
      rules: {
        meetingType: [{ required: true, message: '会议类型不能为空', trigger: 'change' }],
        meetingName: [{ required: true, message: '会议主题不能为空', trigger: 'blur' }],
        meetingContent: [{ required: true, message: '会议议程不能为空', trigger: 'blur' }],
        meetingDate: [{ required: true, message: '时间不能为空', trigger: 'change' }],
        meetingPlace: [{ required: true, message: '时间不能为空', trigger: 'change' }],
        enclosureList: [{ required: true, validator: validFile, trigger: 'change' }],
        userCascader: [{ required: true, message: '时间不能为空', trigger: 'change' }],
      },
      cascaderKeyValueAll: 0,
      userOptions: [],
      userList: [],
      propsCascader: {
        multiple: true,
        label: 'userName',
        value: 'userId',
        children: 'userList',
        emitPath: false,
      },
      roomDiaShow: false,
      isRoomChoose: false,
      roomList: [],
    }
  },
  watch: {
    userOptions(newVal) {
      this.cascaderKeyValueAll++
    },
  },
  created() {},
  mounted() {
    if (this.meetId) {
      this.dealAudit()
    } else {
      this.getGroupUserList('1')
    }
    this.getMeetingRoomList()
  },
  methods: {
    async dealAudit() {
      const { data, code } = await getMeetingDetail({ id: this.meetId })
      if (code === 0) {
        this.formData = Object.assign(this.formData, data)
        this.formData.userName = data.createBy
        this.formData.orgName = data.createByOrg
        this.formData.meetingDate = [data.startTime.slice(0, 16), data.endTime.slice(0, 16)]
        const arr = []
        this.formData.participantsList.forEach(item => {
          arr.push(item.userId)
        })
        this.formData.userCascader = arr || []
        this.getGroupUserList(data.meetingType)
      }
    },
    getGroupUserList(type) {
      const orgId = type === '2' ? 'all' : JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.orgId
      getGroupUserList({ orgId }).then(res => {
        if (res.code === 0) {
          const arr = type === '2' ? res.data.slice(1) : res.data
          const arr1 = []
          arr.forEach(item => {
            if (item.orgId) {
              item.userId = item.orgId
              item.userName = item.orgName
            }
            if (item.userList.length) {
              item.userList.forEach(li => {
                li.orgId = item.orgId
                li.orgName = item.orgName
              })
              arr1.push(...item.userList)
            }
          })
          this.userOptions = arr
          this.userList = arr1
        }
      })
    },
    changeType(val) {
      this.formData.userCascader = []
      this.formData.participantsList = []
      this.getGroupUserList(val)
    },
    saveData(type) {
      if (type !== '0') {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            if (moment(this.formData.meetingDate[0]).format('YYYYMMDDHHmmss') < moment().format('YYYYMMDDHHmmss')) {
              this.$confirm('会议开始时间小于当前时间，确定要提交吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info',
              })
                .then(() => {
                  this.submitData(type)
                })
                .catch()
            } else {
              this.submitData(type)
            }
          }
        })
      } else {
        this.submitData(type)
      }
    },
    submitData(type) {
      if (this.formData.meetingDate.length) {
        this.formData.startTime = this.formData.meetingDate[0] + ':00'
        this.formData.endTime = this.formData.meetingDate[1] + ':00'
      } else {
        this.formData.startTime = ''
        this.formData.endTime = ''
      }
      this.formData.participantsList = []
      if (this.formData.userCascader.length) {
        const arr = []
        for (let i = 0; i < this.formData.userCascader.length; i++) {
          const arr1 = this.userList.filter(item => {
            return item.userId === this.formData.userCascader[i]
          })
          arr.push(arr1[0])
        }
        arr.forEach((item, index) => {
          item.sort = index
        })
        this.formData.participantsList = arr
      }
      this.formData.meetingStatus = type === '0' ? '0' : '1'
      if (this.formData.meetingRoomId) {
        const param = {
          endTime: this.formData.endTime,
          meetingId: this.formData.id || '',
          roomId: this.formData.meetingRoomId,
          roomName: this.formData.meetingPlace,
          startTime: this.formData.startTime,
        }
        checkRoomAndTimeAuthority(param).then(res => {
          if (res.code === 0 && res.data === '1') {
            this.submitMeet(type)
          } else {
            this.$message.warning(res.data)
          }
        })
      } else {
        this.submitMeet(type)
      }
    },
    submitMeet(type) {
      let meetApi
      if (!this.formData.id) {
        meetApi = addMeeting
      } else {
        meetApi = editMeeting
      }
      meetApi(this.formData).then(resR => {
        if (resR.code === 0) {
          if (type === '0') {
            this.$message.success('暂存成功')
            this.$emit('add-content', type)
          } else {
            this.$message.success('提交成功')
            this.$emit('add-content', type)
            this.clearData()
          }
        }
      })
    },
    clearData() {
      this.formData = {
        id: '',
        createTime: moment().format('YYYY-MM-DD'),
        userName: JSON.parse(localStorage.PSKH_USERINFO).userName,
        orgName: JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.orgName,
        meetingType: '1',
        meetingName: '',
        meetingContent: '',
        meetingDate: [],
        meetingPlace: '',
        meetingRoomId: '',
        meetingPlaceType: '2',
        meetingResource: '',
        enclosureList: [],
        participantsList: [],
        meetingStatus: '0',
        startTime: '',
        endTime: '',
        userCascader: [],
      }
    },
    editMeetRoom() {
      if (!this.roomList.length) {
        return this.$message.warning('单位会议室尚未添加，请联系管理员添加会议室后进行选择。')
      }
      if (this.formData.meetingRoomId) {
        this.roomInfo = {
          roomId: this.formData.meetingRoomId,
          startTime: this.formData.startTime.slice(11, 16),
          endTime: this.formData.endTime.slice(11, 16),
        }
      } else {
        this.roomInfo = {}
      }
      this.roomDiaShow = true
    },
    cancleMeet() {
      this.$confirm('确定取消该会议吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      })
        .then(() => {
          this.$emit('cancle-meet', this.meetId)
        })
        .catch()
    },
    chooseMeetRoom(data) {
      this.roomDiaShow = false
      this.isRoomChoose = true
      this.formData.meetingDate = [data.startTime.slice(0, 16), data.endTime.slice(0, 16)]
      this.formData.startTime = data.startTime
      this.formData.endTime = data.endTime
      this.formData.meetingRoomId = data.roomId
      this.formData.meetingPlace = data.roomName
      this.formData.meetingPlaceType = '1'
    },
    onClose() {
      this.roomDiaShow = false
    },
    placeInput() {
      if (!this.isRoomChoose) {
        this.formData.meetingRoomId = ''
        this.formData.meetingPlaceType = '2'
      } else {
        this.isRoomChoose = false
      }
    },
    getMeetingRoomList() {
      getMeetingRoomList({
        date: '',
        meetingId: '',
      }).then(res => {
        if (res.code === 0) {
          this.roomList = res.data || []
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.meet_add {
  width: 100%;
  height: 100%;
  display: flex;
  font-size: 14px;
  .meet_add_l {
    flex: 1;
    padding: 0 10px;
  }
  .color_content {
    color: #909399;
  }
  .notice_form {
    .el-radio {
      margin-right: 10px;
    }
    /deep/.el-input__inner {
      border: 1px solid #dcdfe6;
    }
    .el-date-editor {
      width: auto !important;
    }
    .tip {
      padding-left: 33px;
      margin-top: -15px;
      margin-bottom: 15px;
      color: #d9001b;
    }
    .selectStyle {
      width: 100%;
    }
    .select-btn {
      margin-bottom: 15px;
      padding-left: 100px;
    }
  }
  .btn_save {
    margin-top: 10px;
    text-align: center;
    padding-bottom: 10px;
    .el-button {
      margin: 0 20px;
    }
  }
}
</style>
